<script setup>
import { message } from "ant-design-vue";
import { ref, onMounted } from "vue";
import { useRouter } from "vue-router";
import { getLoginUser, userLogin } from "@/api/user";

const router = useRouter();
const formState = ref({
  username: "",
  password: "",
});
const formRef = ref();
const rules = {
  username: [{ required: true, message: "请输入用户名", trigger: "blur" }],
  password: [{ required: true, message: "请输入密码", trigger: "blur" }],
};

const onSubmit = () => {
  formRef.value
    .validate()
    .then(async () => {
      let { data } = await userLogin(formState.value);
      if (data.code != 200) {
        message.error(data.message);
        return;
      }
      message.success(data.message);
      router.push({ name: "AdminIndex" });
    })
    .catch((error) => {
      console.log("error", error);
    });
};

onMounted(async () => {
  // 未登录会直接抛出异常
  await getLoginUser();
  router.push({ name: "AdminIndex" });
});
</script>

<template>
  <div class="content">
    <a-row type="flex" justify="center" style="margin-top: 100px">
      <a-col :md="6" :xs="21" :sm="21">
        <a-card title="服务器列表 - 用户登录">
          <a-form :model="formState" :rules="rules" ref="formRef">
            <a-form-item name="username">
              <a-input v-model:value="formState.username" placeholder="用户名" />
            </a-form-item>
            <a-form-item name="password">
              <a-input v-model:value="formState.password" type="password" placeholder="密码" />
            </a-form-item>
            <a-form-item>
              <a-button type="primary" @click="onSubmit">登录</a-button>
              <a-button style="margin-left: 10px" @click="router.push({ name: 'Reg' })">注册账号</a-button>
            </a-form-item>
          </a-form>
        </a-card>
      </a-col>
    </a-row>
  </div>
</template>

<style scoped>
.content {
  position: fixed;
  width: 100%;
  background-image: url("../assets/sign_bg.png");
  background-repeat: no-repeat;
  background-color: #b8e5f8;
  background-size: cover;
  height: 100vh;
}
</style>
